/*
 * THE FOLLOWING FIRMWARE IS PROVIDED: (1) "AS IS" WITH NO WARRANTY; AND 
 * (2)TO ENABLE ACCESS TO CODING INFORMATION TO GUIDE AND FACILITATE CUSTOMER.
 * CONSEQUENTLY, SEMTECH SHALL NOT BE HELD LIABLE FOR ANY DIRECT, INDIRECT OR
 * CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE CONTENT
 * OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING INFORMATION
 * CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
 * 
 * Copyright (C) SEMTECH S.A.
 */
/*! 
 * \file       sx1276-Hal.c
 * \brief      SX1276 Hardware Abstraction Layer
 *
 * \version    2.0.B2 
 * \date       Nov 21 2012
 * \author     Miguel Luis
 *
 * Last modified by Miguel Luis on Jun 19 2013
 */
#include <stdint.h>
#include <stdbool.h> 
#include "main.h"
#include "spi.h"
#include "gpio.h"
#include "platform.h"
#include "../../radio/sx1276-Hal.h"


uint8_t SpiInOut( uint8_t outData )
{
	uint8_t Rxdata;
	HAL_SPI_TransmitReceive(&hspi1,&outData,&Rxdata,1, 1000);       
 	return Rxdata; 
	
}


void SX1276InitIo( void )
{

}

void SX1276SetReset( uint8_t state )
{
	if(state==RADIO_RESET_ON)
	{
			HAL_GPIO_WritePin(LRST_GPIO_Port,LRST_Pin,GPIO_PIN_RESET);
	}
	else 
	{
			HAL_GPIO_WritePin(LRST_GPIO_Port,LRST_Pin,GPIO_PIN_SET);
	}
}

void SX1276Write( uint8_t addr, uint8_t data )
{
    SX1276WriteBuffer( addr, &data, 1 );
}

void SX1276Read( uint8_t addr, uint8_t *data )
{
    SX1276ReadBuffer( addr, data, 1 );
}

void SX1276WriteBuffer( uint8_t addr, uint8_t *buffer, uint8_t size )
{

	HAL_GPIO_WritePin(SPI1_CS_GPIO_Port,SPI1_CS_Pin,GPIO_PIN_RESET);
	SpiInOut( addr | 0x80 );
	for(uint8_t i = 0; i < size; i++ )
	{
			SpiInOut( buffer[i] );
	}
	HAL_GPIO_WritePin(SPI1_CS_GPIO_Port,SPI1_CS_Pin,GPIO_PIN_SET);
	
}

void SX1276ReadBuffer( uint8_t addr, uint8_t *buffer, uint8_t size )
{

	HAL_GPIO_WritePin(SPI1_CS_GPIO_Port,SPI1_CS_Pin,GPIO_PIN_RESET);
	SpiInOut( addr & 0x7F );

	for(uint8_t i = 0; i < size; i++ )
	{
			buffer[i] = SpiInOut( 0 );
	}
	HAL_GPIO_WritePin(SPI1_CS_GPIO_Port,SPI1_CS_Pin,GPIO_PIN_SET);

}

void SX1276WriteFifo( uint8_t *buffer, uint8_t size )
{
    SX1276WriteBuffer( 0, buffer, size );
}

void SX1276ReadFifo( uint8_t *buffer, uint8_t size )
{
    SX1276ReadBuffer( 0, buffer, size );
}

inline uint8_t SX1276ReadDio0( void )
{
	return HAL_GPIO_ReadPin(DIO0_GPIO_Port,DIO0_Pin);
}

inline uint8_t SX1276ReadDio1( void )
{
  return HAL_GPIO_ReadPin(DIO1_GPIO_Port,DIO1_Pin);
}

inline uint8_t SX1276ReadDio2( void )
{
  return 0;
}

inline uint8_t SX1276ReadDio3( void )
{
	return HAL_GPIO_ReadPin(DIO3_GPIO_Port,DIO3_Pin);
}

inline uint8_t SX1276ReadDio4( void )
{
	return 1;
}

inline uint8_t SX1276ReadDio5( void )
{
	return 1;
}

inline void SX1276WriteRxTx( uint8_t txEnable )
{

}

